package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"share-chat/api/request"
	"share-chat/internal/model"
	"share-chat/pkg"
	"time"
)

func AddShare(c *gin.Context) {
	var req request.AddShareForm
	var share model.Share

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "验证失败",
			"data":    "",
		})
		return
	}

	share = model.Share{
		UserId:  req.UserId,
		Title:   req.Title,
		Content: req.Content,
		Image:   req.Image,
		Video:   req.Video,
	}

	err := share.AddShare()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "分享失败",
			"data":    "",
		})
		return
	}

	rabbitmq := pkg.NewRabbitMQSimple("" +
		"rabbit")

	//生产进队列
	marshal, err := json.Marshal(share)
	if err != nil {
		return
	}

	rabbitmq.PublishSimple(string(marshal))
	time.Sleep(1 * time.Second)

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "分享成功",
		"data":    "",
	})

}

func UpdatedStatusShare(c *gin.Context) {

	go mainSimpleRecieve()
}

func mainSimpleRecieve() {
	rabbitmq := pkg.NewRabbitMQSimple("" +
		"rabbit")
	rabbitmq.ConsumeSimple()
}

func ListShare(c *gin.Context) {
	var share model.Share

	listShare, err := share.ListShare()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "查看失败",
			"data":    err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "查看成功",
		"data":    listShare,
	})
}
